from django.db import models
from django.utils import timezone
from django.contrib.auth import get_user_model
from parser.models import ParsedQuestion

User = get_user_model()

class ExerciseSet(models.Model):
    """练习集模型，用于组织一组练习题"""
    title = models.CharField('标题', max_length=200)
    description = models.TextField('描述', blank=True, null=True)
    created_by = models.ForeignKey(User, on_delete=models.CASCADE, related_name='created_exercise_sets', verbose_name='创建者')
    created_at = models.DateTimeField('创建时间', default=timezone.now)
    updated_at = models.DateTimeField('更新时间', auto_now=True)
    is_public = models.BooleanField('是否公开', default=False)
    
    class Meta:
        verbose_name = '练习集'
        verbose_name_plural = verbose_name
        ordering = ['-created_at']
    
    def __str__(self):
        return self.title
    
    @property
    def questions_count(self):
        """获取练习集中的题目数量"""
        return self.questions.count()

class Exercise(models.Model):
    """练习题模型"""
    DIFFICULTY_CHOICES = (
        ('easy', '简单'),
        ('medium', '中等'),
        ('hard', '困难'),
    )
    
    exercise_set = models.ForeignKey(ExerciseSet, on_delete=models.CASCADE, related_name='questions', verbose_name='所属练习集')
    content = models.TextField('题目内容')
    answer = models.TextField('参考答案', blank=True, null=True)
    explanation = models.TextField('解析', blank=True, null=True)
    question_type = models.CharField('题目类型', max_length=50, blank=True, null=True)
    difficulty = models.CharField('难度', max_length=10, choices=DIFFICULTY_CHOICES, default='medium')
    created_at = models.DateTimeField('创建时间', default=timezone.now)
    updated_at = models.DateTimeField('更新时间', auto_now=True)
    source_question = models.ForeignKey(ParsedQuestion, on_delete=models.SET_NULL, null=True, blank=True, related_name='exercises', verbose_name='来源题目')
    
    class Meta:
        verbose_name = '练习题'
        verbose_name_plural = verbose_name
        ordering = ['exercise_set', 'id']
    
    def __str__(self):
        return f"{self.exercise_set.title} - 题目{self.id}"

class UserExerciseRecord(models.Model):
    """用户练习记录模型"""
    STATUS_CHOICES = (
        ('correct', '正确'),
        ('incorrect', '错误'),
        ('skipped', '跳过'),
        ('marked', '标记'),
    )
    
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='exercise_records', verbose_name='用户')
    exercise = models.ForeignKey(Exercise, on_delete=models.CASCADE, related_name='user_records', verbose_name='练习题')
    user_answer = models.TextField('用户答案', blank=True, null=True)
    status = models.CharField('状态', max_length=20, choices=STATUS_CHOICES, default='skipped')
    created_at = models.DateTimeField('创建时间', default=timezone.now)
    updated_at = models.DateTimeField('更新时间', auto_now=True)
    
    class Meta:
        verbose_name = '练习记录'
        verbose_name_plural = verbose_name
        ordering = ['-updated_at']
        unique_together = ['user', 'exercise']
    
    def __str__(self):
        return f"{self.user.username} - {self.exercise.exercise_set.title} - 题目{self.exercise.id}"

class UserExerciseSetProgress(models.Model):
    """用户练习集进度模型"""
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='exercise_set_progress', verbose_name='用户')
    exercise_set = models.ForeignKey(ExerciseSet, on_delete=models.CASCADE, related_name='user_progress', verbose_name='练习集')
    completed_count = models.IntegerField('已完成题目数', default=0)
    correct_count = models.IntegerField('正确题目数', default=0)
    last_exercise = models.ForeignKey(Exercise, on_delete=models.SET_NULL, null=True, blank=True, related_name='+', verbose_name='上次练习题')
    started_at = models.DateTimeField('开始时间', default=timezone.now)
    last_activity_at = models.DateTimeField('最后活动时间', auto_now=True)
    is_completed = models.BooleanField('是否完成', default=False)
    
    class Meta:
        verbose_name = '练习集进度'
        verbose_name_plural = verbose_name
        ordering = ['-last_activity_at']
        unique_together = ['user', 'exercise_set']
    
    def __str__(self):
        return f"{self.user.username} - {self.exercise_set.title} - 进度"
    
    @property
    def progress_percentage(self):
        """计算完成百分比"""
        total = self.exercise_set.questions_count
        if total == 0:
            return 0
        return round((self.completed_count / total) * 100, 2)
